/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.huawei.codecheck.uccp.plugin.utils.http;

import org.apache.http.HttpResponse;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;

/**
 * http重试策略
 *
 * @since 2019-09-23
 */
public class HttpServiceRetryStrategy implements ServiceUnavailableRetryStrategy {
    private static final int HTTP_RETRY_TIMES = 10;

    /**
     * 重试间隔时间，单位millisecond
     */
    private static final int HTTP_RETRY_INTERVAL = 10_000;

    private final int maxRetries;

    private final long retryInterval;

    /**
     * HttpServiceRetryStrategy构造函数
     *
     * @param maxRetries 最大重试次数
     * @param retryInterval 重试的间隔
     */
    public HttpServiceRetryStrategy(int maxRetries, int retryInterval) {
        Args.positive(maxRetries, "Max retries");
        Args.positive(retryInterval, "Retry interval");
        this.maxRetries = maxRetries;
        this.retryInterval = (long) retryInterval;
    }

    /**
     * HttpServiceRetryStrategy构造函数
     */
    public HttpServiceRetryStrategy() {
        this.maxRetries = HTTP_RETRY_TIMES;
        this.retryInterval = HTTP_RETRY_INTERVAL;
    }

    @Override
    public boolean retryRequest(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
        if (executionCount >= maxRetries) {
            return false;
        }
        if (httpResponse.getStatusLine().getStatusCode() < 200
            || httpResponse.getStatusLine().getStatusCode() > 300) {
            return true;
        }
        return false;
    }

    @Override
    public long getRetryInterval() {
        return retryInterval;
    }
}
